package GuiTools;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

import javax.swing.*;
import javax.swing.border.TitledBorder;

import Mainframe.Mainframe;
import Settings.Language;
import Settings.Settings;
import Storage.Storage;
import Storage.Vocabulary;
import Storage.Word;

public class TribuitWordChooser {
	public TribuitFrame preTestFrame, wtFrame;
	public JRadioButton lang1RB, lang2RB;
	public JCheckBox[] lectionsCB;
	public Vector<JCheckBox> tcCB;
	public JPanel cbPanel, lectionsPanel, centerPanel, lectionsPanePanel,tcPanePanel;
	public JComboBox preCB;
	public Vector<String> availableSections;
	public JButton allSectionsBtn, allTCBtn, preTestOkBtn;
	public JLabel wordsLabel;
	public Storage MAINVOC;
	public Settings SET;
	public Language LANG;
	public Mainframe MAINFRAME;
	public Color BGCOLOR = new Color(255, 126, 0);
	public boolean TESTLANG2;
	public Vector<Word> testvocabulary;
	public Vector<JPanel> bPanels = new Vector<JPanel>(),aPanels = new Vector<JPanel>();
	public Color bgCol;;
	public JScrollPane jsp;
	public String headerText, firstLanguageTitle, vocNameA, vocNameB;

	public TribuitWordChooser(Storage stor, Settings set, Mainframe fr, String headerTxt, String firstLangTitle) {
		MAINVOC = stor;
		SET = set;
		LANG = SET.getLanguage();
		MAINFRAME = fr;
		headerText = headerTxt;
		firstLanguageTitle = firstLangTitle;
		if (MAINVOC.noWordsAtAll())JOptionPane.showMessageDialog(MAINFRAME, LANG.getErrorWordcheckNoWords());
	}

	public void buildGUI() {
		preTestFrame = new TribuitFrame(LANG.getWckPreselectionHeader());
		preCB = new JComboBox();
		preCB.setPreferredSize(new Dimension(180,26));
		Vocabulary[] tmp_all_voc = MAINVOC.getVocabularies();
		// let not choose empty vocabularies
		for (int i = 0; i < tmp_all_voc.length; i++) {
			if (tmp_all_voc[i].hasWords()) preCB.addItem(tmp_all_voc[i].getName());
		}
		preCB.addItemListener(new preCBListener());
		cbPanel = new JPanel();
		cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.Y_AXIS));
		lectionsPanel = new JPanel();
		lectionsPanel.setLayout(new BoxLayout(lectionsPanel, BoxLayout.Y_AXIS));
		// setCBPanels(false);
		JScrollPane lectionsPane = new JScrollPane(lectionsPanel);
		lectionsPane.setPreferredSize(new Dimension(100, 120));
		lectionsPane.getVerticalScrollBar().setUnitIncrement(30);
		lectionsPanePanel = new JPanel();
		lectionsPanePanel.setLayout(new BoxLayout(lectionsPanePanel, BoxLayout.Y_AXIS));
		tcPanePanel = new JPanel();
		tcPanePanel.setLayout(new BoxLayout(tcPanePanel, BoxLayout.Y_AXIS));
		JScrollPane tcPane = new JScrollPane(cbPanel);
		tcPane.setPreferredSize(new Dimension(150, 120));
		tcPane.getVerticalScrollBar().setUnitIncrement(30);
		allSectionsBtn = new JButton(LANG.getNone());
		allSectionsBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (allSectionsBtn.getText().equals(LANG.getAll())) {
					allSectionsBtn.setText(LANG.getNone());
					for (JCheckBox c : lectionsCB)
						c.setSelected(true);
				} else {
					allSectionsBtn.setText(LANG.getAll());
					for (JCheckBox c : lectionsCB)
						c.setSelected(false);
				}
				generateTestVocabulary();
				preTestFrame.pack();
			}
		});
		allTCBtn = new JButton(LANG.getNone());
		allTCBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (allTCBtn.getText().equals(LANG.getAll())) {
					allTCBtn.setText(LANG.getNone());
					for (JCheckBox c : tcCB)
						c.setSelected(true);
				} else {
					allTCBtn.setText(LANG.getAll());
					for (JCheckBox c : tcCB)
						c.setSelected(false);
				}
				generateTestVocabulary();
				preTestFrame.pack();
			}
		});
		lectionsPanePanel.add(lectionsPane);
		lectionsPanePanel.add(allSectionsBtn);
		tcPanePanel.add(tcPane);
		tcPanePanel.add(allTCBtn);
		preTestOkBtn = new JButton("ok");
		JButton preTestCancelBtn = new JButton(LANG.getCancel());
		preTestOkBtn.addActionListener(new preTestOkBtnListener());
		preTestCancelBtn.addActionListener(new preTestCancelBtnListener());
		
		// testlanguage-panel:
		Vocabulary tmp_vocab = MAINVOC.getVocabulary((String) preCB.getSelectedItem());
		lang1RB = new JRadioButton(tmp_vocab.getNameA(), true);
		lang1RB.setPreferredSize(new Dimension(100,26));
		lang1RB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				TESTLANG2 = false;
			}
		});
		lang2RB = new JRadioButton(tmp_vocab.getNameB());
		lang2RB.setPreferredSize(new Dimension(100,26));
		lang2RB.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				TESTLANG2 = true;
			}
		});
		ButtonGroup bg = new ButtonGroup();
		bg.add(lang1RB);
		bg.add(lang2RB);
		JPanel langRbPanel = new JPanel();
		langRbPanel.setLayout(new BoxLayout(langRbPanel, BoxLayout.Y_AXIS));
		langRbPanel.add(lang1RB);
		langRbPanel.add(lang2RB);
		JPanel firstLanguagePanel = new JPanel();
		firstLanguagePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black, 3), LANG.getFirstGivenLanguage()+ ":", TitledBorder.DEFAULT_JUSTIFICATION,TitledBorder.DEFAULT_POSITION, new Font(Font.SANS_SERIF,Font.BOLD | Font.ITALIC, 16)));
		firstLanguagePanel.add(new LabelPanel(LANG.getVocabulary() + ":", preCB));
		firstLanguagePanel.add(new LabelPanel(firstLanguageTitle + ":",langRbPanel));

		// word counter
		JPanel wordsPanel = getWordsPanel();

		// optionPanel
		JPanel optionPanel = new JPanel();
		optionPanel.add(optionPanel());
		optionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black, 3), LANG.getOptions() + ":",TitledBorder.DEFAULT_JUSTIFICATION,TitledBorder.DEFAULT_POSITION, new Font(Font.SANS_SERIF,Font.BOLD | Font.ITALIC, 16)));

		// buttons
		JPanel prebtnPanel = new JPanel();
		prebtnPanel.add(preTestOkBtn);
		prebtnPanel.add(preTestCancelBtn);
		prebtnPanel.setBackground(BGCOLOR);
		JPanel preCenterPanel = new JPanel();
		GridBagConstraints preTgbc = new GridBagConstraints();
		preCenterPanel.setLayout(new GridBagLayout());
		preTgbc.gridy++;
		preTgbc.insets = new Insets(10, 10, 10, 10);
		preTgbc.fill = GridBagConstraints.BOTH;
		preTgbc.anchor = GridBagConstraints.NORTHWEST;
		preTgbc.gridwidth = 1;
		preCenterPanel.add(firstLanguagePanel, preTgbc);
		preTgbc.gridx = 1;
		preCenterPanel.add(optionPanel, preTgbc);
		preTgbc.gridwidth = 2;
		preTgbc.gridy++;
		preTgbc.gridx = 0;
		preCenterPanel.add(groupsPanel(), preTgbc);
		preTgbc.gridwidth = 3;
		preTgbc.gridy++;
		preTgbc.fill = GridBagConstraints.NONE;
		preCenterPanel.add(wordsPanel, preTgbc);
		preCenterPanel.setBackground(Color.darkGray);
		preTestFrame.addPanel("north", new Header(LANG.getWckPreselectionHeader()+ " - " + headerText));
		preTestFrame.addPanel("center", preCenterPanel);
		preTestFrame.addPanel("south", prebtnPanel);
		preTestFrame.showUp(400, 500, 300, 100);
		preTestFrame.pack();
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				updatePreCB();
			}
		});
	}


	class preCBListener implements ItemListener {
		public void itemStateChanged(ItemEvent e) {
			updatePreCB();
		}
	}

	public void updatePreCB() {
		Vocabulary voc = MAINVOC.getVocabulary((String) preCB.getSelectedItem());
		lang1RB.setText(voc.getNameA());
		lang2RB.setText(voc.getNameB());
		updateTermClassCB();
		updateSections();
		allSectionsBtn.setText(LANG.getAll());
		generateTestVocabulary();
		preTestFrame.repaint();
	}

	public class tcCBListener implements ItemListener {
		public void itemStateChanged(ItemEvent e) {
			updateSections();
		}
	}

	public void updateTermClassCB(){
		Vocabulary tmpVoc = MAINVOC.getVocabulary(preCB.getSelectedItem().toString());
		Word[] words = tmpVoc.getWords();
		tcCB = new Vector<JCheckBox>();
		Vector<String> existingTermClasses = new Vector<String>();
		String tmpTC;
		for (Word w : words) {
			tmpTC = w.getTermclassA() + " / " + w.getTermclassB();
			if (!existingTermClasses.contains(tmpTC))
				existingTermClasses.add(tmpTC);
		}
		cbPanel.removeAll();
		JCheckBox jcb;
		for (String s : existingTermClasses) {
			jcb = new JCheckBox(s, true);
			tcCB.add(jcb);
			jcb.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
			jcb.addItemListener(new tcCBListener());
			cbPanel.add(jcb);
		}
		preTestFrame.pack();
		preTestFrame.repaint();
	}
	
	public void updateSections() {
		// find sections containing words of the selected term class
		Vector<String> selectedTermClasses = new Vector<String>();
		for (JCheckBox tcJCB : tcCB) {
			if (tcJCB.isSelected())selectedTermClasses.add(tcJCB.getText());
		}
		Word[] wordsTmp = MAINVOC.getVocabulary(preCB.getSelectedItem().toString()).getWords();
		String tc, section;
		availableSections = new Vector<String>();
		for (Word w : wordsTmp) {
			tc = w.getTermclassA() + " / " + w.getTermclassB();
			if (selectedTermClasses.contains(tc)) {
				section = w.getLection();
				if (!availableSections.contains(section))
					availableSections.add(section);
			}
		}
		// sorting the selected sections
		ArrayList<String> sectionWords = new ArrayList<String>();
		ArrayList<Integer> sectionNumbers = new ArrayList<Integer>();
		Integer in;
		// split numbers from words
		for (int i = 0; i < availableSections.size(); i++) {
			section = availableSections.elementAt(i);
			try {
				in = Integer.parseInt(section);
				if (!sectionNumbers.contains(in))sectionNumbers.add(in);
			}
			catch (Exception e) {
				if (!sectionWords.contains(section))sectionWords.add(section);
			}
		}
		availableSections.removeAllElements();
		if (sectionNumbers.size() > 0) {
			Collections.sort(sectionNumbers);
			for (int number : sectionNumbers) {
				availableSections.add("" + number);
			}
		}
		if (sectionWords.size() > 0) {
			Collections.sort(sectionWords, String.CASE_INSENSITIVE_ORDER);
			for (String word : sectionWords) {
				availableSections.add(word);
			}
		}
		lectionsPanel.removeAll();
		lectionsCB = new JCheckBox[availableSections.size()];
		String toAdd;
		for (int i = 0; i < availableSections.size(); i++) {
			toAdd = availableSections.elementAt(i).toString();
			lectionsCB[i] = new JCheckBox((toAdd.equals("~") || toAdd.equals("~~~")) ? LANG.getUnsorted() : toAdd, false);
			lectionsCB[i].setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
			lectionsPanel.add(lectionsCB[i]);
			lectionsCB[i].addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					for(JCheckBox cb : lectionsCB){
						if(cb.isSelected()){
							allSectionsBtn.setText(LANG.getNone());
							preTestFrame.pack();
							return;
						}
					}
					allSectionsBtn.setText(LANG.getAll());
				}
			});
			lectionsCB[i].addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					generateTestVocabulary();
				}
			});
		}
		preTestFrame.pack();
		preTestFrame.repaint();
	}

	class preTestOkBtnListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (testvocabulary != null && testvocabulary.size() > 0) {
				preTestFrame.dispose();
				okAction(preCB.getSelectedItem().toString(), testvocabulary);
			}
			else JOptionPane.showMessageDialog(preTestFrame, LANG.getErrorWckChooseAtLeast(),LANG.getAttention(),JOptionPane.WARNING_MESSAGE);
		}
	}

	public void generateTestVocabulary() {
		Vocabulary tmpVoc = MAINVOC.getVocabulary((String) preCB.getSelectedItem());
		testvocabulary = new Vector<Word>();
		vocNameA = tmpVoc.getNameA();
		vocNameB = tmpVoc.getNameB();
		Word[] wordList = tmpVoc.getWords();
		Vector<String> tcSelection = new Vector<String>();
		Vector<String> secSelection = new Vector<String>();
		for (JCheckBox tcJCB : tcCB) {
			if (tcJCB.isSelected())
				tcSelection.add(tcJCB.getText());
		}
		for (JCheckBox jcb : lectionsCB) {
			if (jcb.isSelected())secSelection.add(jcb.getText());
		}
		if(tcSelection.size() > 0 && secSelection.size() > 0) {
			String wSection;
			for (int i = 0; i < wordList.length; i++) {
				wSection = wordList[i].getLection();
				if(tcSelection.contains(wordList[i].getTermclassA() + " / " + wordList[i].getTermclassB())) {
					if(wSection.equals("~") && secSelection.contains(LANG.getUnsorted())) {
						testvocabulary.add(wordList[i]);
					}
					else{
						if (secSelection.contains(wSection)) testvocabulary.add(wordList[i]);
					}
				}
			}
			wordsLabel.setText("" + testvocabulary.size());
		}
		else {
			wordsLabel.setText("0");
		}
	}

	public class GroupsPanel extends JPanel {
		public GroupsPanel() {
			super();
			this.setLayout(new GridBagLayout());
			GridBagConstraints gpGBC = new GridBagConstraints();
			gpGBC.anchor = GridBagConstraints.NORTHWEST;
			gpGBC.insets = new Insets(5, 5, 5, 5);
			this.add(new LabelPanel(LANG.getTermclasses() + ":", tcPanePanel),gpGBC);
			gpGBC.gridx = 2;
			this.add(new LabelPanel(LANG.getLections() + ":",lectionsPanePanel), gpGBC);
			this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black, 3), LANG.getWordgroups()+ ":", TitledBorder.DEFAULT_JUSTIFICATION,TitledBorder.DEFAULT_POSITION, new Font(Font.SANS_SERIF,Font.BOLD | Font.ITALIC, 16)));
		}
	}

	class preTestCancelBtnListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			cancelAction();
			preTestFrame.dispose();
		}
	}

	public boolean getTestLanguage2() {
		return TESTLANG2;
	}

	public JPanel getWordsPanel() {
		wordsLabel = new JLabel("0");
		JLabel wordsLabelLabel = new JLabel(LANG.getWords() + ": ");
		JPanel wordsPanel = new JPanel();
		wordsPanel.add(wordsLabelLabel);
		wordsPanel.add(wordsLabel);
		return wordsPanel;
	}

	public JPanel groupsPanel() {
		return new GroupsPanel();
	}

	public JPanel optionPanel() {
		return new JPanel();
	}

	public void okAction(String vocName, Vector<Word> words) {
	}

	public void cancelAction() {
	}
}// preTest-class